package architecture.demo13;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    private static final int PORT = 8888;
    private ContactList contactList;

    public Server() {
        this.contactList = new ContactList();
    }

    public void start() {
        try {
            ServerSocket serverSocket = new ServerSocket(PORT);
            System.out.println("服务器已启动，等待客户端连接...");

            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端已连接：" + clientSocket.getInetAddress());

                // 创建新的线程处理客户端请求
                Thread clientThread = new Thread(() -> {
                    try {
                        ObjectOutputStream outputStream = new ObjectOutputStream(clientSocket.getOutputStream());
                        ObjectInputStream inputStream = new ObjectInputStream(clientSocket.getInputStream());

                        while (true) {
                            // 接收客户端发送的消息
                            Message message = (Message) inputStream.readObject();
                            processMessage(message);

                            // 发送响应消息给客户端
                            outputStream.writeObject(message);
                            outputStream.flush();
                        }
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            clientSocket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });

                clientThread.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void processMessage(Message message) {
        switch (message.getOperation()) {
            case ADD:
                Contact contact = (Contact) message.getData();
                contactList.addContact(contact);
                break;
            case SEARCH:
                String keyword = (String) message.getData();
                contactList.searchContacts(keyword);
                break;
            case REMOVE:
                Contact contactToRemove = (Contact) message.getData();
                contactList.removeContact(contactToRemove);
                break;
            case UPDATE:
                Contact[] contactsToUpdate = (Contact[]) message.getData();
                contactList.updateContact(contactsToUpdate[0], contactsToUpdate[1]);
                break;
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }
}

